package com.talent.jiwen.teacher;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.home.SendOrderActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.ApplyTeacherResult;
import com.talent.jiwen.ui.widgets.TagView;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

public class OrderedTeacherListActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    private String orderId;
    private boolean showOption = true;

    private static final String PARAM_ORDER_ID = "param.order.id";
    private static final String PARAM_CREATOR_ID = "param.creator.id";

    public static final String EVENT_FINISH_ACTIVITY = "event.finish.activity";

    private List<ApplyTeacherResult.ApplyTeacherInfo> dataList = new ArrayList<>();
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_ordered_teacher_list;
    }

    @Override
    public String titleName() {
        return getString(R.string.ordered);
    }

    @Override
    protected void initData() {

        registEventBus();

        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);
        String creatorId = getIntent().getStringExtra(PARAM_CREATOR_ID);

        if (creatorId.equals(SPUtil.getUserId())){
            showOption = true;
        }else{
            showOption = false;
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(new CommonAdapter<ApplyTeacherResult.ApplyTeacherInfo>(this , R.layout.item_order_teacher , dataList){
            @Override
            protected void convert(ViewHolder holder, final ApplyTeacherResult.ApplyTeacherInfo data, int position) {
                ImageView teacherIv = holder.getView(R.id.teacherIv);
                TextView nameTv = holder.getView(R.id.nameTv);
                TextView desTv = holder.getView(R.id.desTv);
                TextView priceTv = holder.getView(R.id.priceTv);
                TextView optionTv = holder.getView(R.id.optionTv);
                TagView tagView = holder.getView(R.id.tagView);
                ImageView teachFlagIv = holder.getView(R.id.teachFlagIv);
                TextView schoolTv = holder.getView(R.id.schoolTv);

                ImageUtil.loadCorner4Image(OrderedTeacherListActivity.this , data.getTeacherHeadImage() , teacherIv);
                nameTv.setText(data.getTeacherName());

                if (data.getTeacherType() == 1){
                    //在校名师
                    teachFlagIv.setImageResource(R.mipmap.iv_teacher_flag);
                    schoolTv.setVisibility(View.GONE);
                }else if (data.getTeacherType() == 2){
                    //名校学霸
                    teachFlagIv.setImageResource(R.mipmap.iv_student_flag);
                    if(Validators.isEmpty(data.getGraduatedSchoolName())){
                        schoolTv.setVisibility(View.GONE);
                    }else{
                        schoolTv.setVisibility(View.VISIBLE);
                        schoolTv.setText("("+data.getGraduatedSchoolName() +"在读)");
                    }
                }

                float score = (Float.parseFloat(data.getEffectScore()) +Float.parseFloat(data.getServeScore())) / 2;
                desTv.setText("评分 " + score + "    解决次数  " + data.getSolveCount());
                priceTv.setText(data.getTeachPrice() + "元/分钟");
                tagView.bindData(data.getTagInfo());

                if (showOption){
                    optionTv.setVisibility(View.VISIBLE);
                    optionTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            acceptTeacher(data.getTeacherId());

                        }
                    });
                }else{
                    optionTv.setVisibility(View.GONE);
                }

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TeacherDetailActivity.startTeacherDetailActivity(OrderedTeacherListActivity.this , TeacherDetailActivity.TYPE_ACCEPT_COURSE , data.getTeacherId() , orderId);
                    }
                });
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getApplyTeacherList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();
    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(EVENT_FINISH_ACTIVITY)){
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    /**获取教师申请列表
     *
     */
    private void getApplyTeacherList(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().getApplyTeacherList(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<ApplyTeacherResult>(OrderedTeacherListActivity.this) {
            @Override
            protected void _onNext(ApplyTeacherResult applyTeacherResult) {
                dataList.clear();
                dataList.addAll(applyTeacherResult.getApplyList());

                recyclerView.getAdapter().notifyDataSetChanged();

                refreshLayout.finishRefresh();

                if (Validators.isEmpty(dataList)){
                    noDataIv.setVisibility(View.VISIBLE);
                }else{
                    noDataIv.setVisibility(View.GONE);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**接受教师
     *
     * @param teacherId
     */
    private void acceptTeacher(String teacherId){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , teacherId);
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().acceptTeacher(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(OrderedTeacherListActivity.this) {
            @Override
            protected void _onNext(Void v) {
                EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }


    /**启动该页面
     *
     * @param context
     * @param orderId
     */
    public static void startTeacherListActivity(Context context , String orderId , String creatorId){
        Intent intent = new Intent();
        intent.setClass(context , OrderedTeacherListActivity.class);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        intent.putExtra(PARAM_CREATOR_ID  , creatorId);
        context.startActivity(intent);

    }
}
